#import <objc/runtime.h>
#import "MRPageController.h"

@interface MRPageController ()

@property (nonatomic, strong) UIView		*snapshot;
@property (nonatomic, assign) NSInteger		currentPage;

@end

/*===================================================================
 说明:
	页面控制器
 ==================================================================*/
@implementation MRPageController

- (void)viewDidLoad
{
	[super viewDidLoad];
	self.automaticallyAdjustsScrollViewInsets = NO;
	
	_buttons = [NSMutableArray array];
	_lastPage = -1;
	
	_leftItemsCount = self.navigationItem.leftBarButtonItems.count;
	_rightItemsCount = self.navigationItem.rightBarButtonItems.count;
	
	//获取子视图中的集合视图
	for (UICollectionView *view in self.view.subviews)
	{
		if ([view isKindOfClass:[UICollectionView class]])
		{
			_collectionView = view;
			break;
		}
	}
	
	//如果标题非视图才搜索Toolbar
	if (!_selectView && !self.navigationItem.titleView)
	{
		[self.view viewWithClass:[UIToolbar class] handler:^(id view, BOOL *stop) {
			_selectView = view;
			*stop = YES;
		}];
	}
	
	//导航栏优先为选择视图
	if (!_selectView)
	{
		[self.view viewWithClass:[UINavigationBar class] handler:^(id view, BOOL *stop) {
			_selectView = view;
			self.navigationItem.hidesLine = YES;
			*stop = YES;
		}];
	}
	
	//默认使用导航标题视图作为选择器
	if (!_selectView) _selectView = self.navigationItem.titleView;
	
	//初始化集合视图
	if (!self.collectionView)
	{
		UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
		layout.minimumInteritemSpacing = 0;
		layout.minimumLineSpacing = 0;
		layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
		
		_collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
		self.collectionView.backgroundColor = [UIColor clearColor];
		
		[self.view insertSubview:self.collectionView atIndex:0];
		[self.collectionView addConstraintEqualSuperview:self.view];
		[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
		
		if (self.collectionView.panGestureRecognizer && self.navigationController)
			[self.collectionView.panGestureRecognizer requireGestureRecognizerToFail:self.navigationController.panGestureRecognizer];
		
		[self.collectionView layoutIfNeeded];
	}
	
	self.collectionView.delegate = self;
	self.collectionView.dataSource = self;
	self.collectionView.bounces = NO;
	self.collectionView.scrollsToTop = NO;
	self.collectionView.pagingEnabled = YES;
	self.collectionView.showsVerticalScrollIndicator = NO;
	self.collectionView.showsHorizontalScrollIndicator = NO;
}

/*===================================================================
 说明：
	检测选择视图
 ==================================================================*/
- (void)viewWillCreate
{
	if (_selectView && ![_selectView isKindOfClass:[UISegmentedControl class]])
	{
		[_buttons removeAllObjects];
		
		[_selectView viewWithClass:[UIButton class] handler:^(UIButton *btn, BOOL *stop) {
			
			[btn addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
			
			[btn setTitleColor:[[MRSkinManager skin].mainTextColor colorWithAlphaComponent:.9] forState:UIControlStateNormal];
			[btn setTitleColor:[MRSkinManager skin].mainTextColor forState:UIControlStateHighlighted];
			[btn setTitleColor:[MRSkinManager skin].skinColor forState:UIControlStateSelected];
			
			[_buttons insertObject:btn atIndex:0];
		}];
		
		_pageCount = _buttons.count;
		
		for (NSInteger i=0; i<_pageCount; i++)
		{
			if (i < self.childViewControllers.count)
			{
				//UIViewController <MRPageDelegate> *vc = self.childViewControllers[i];
				//NSString *title = [vc respondsToSelector:@selector(pageTitle)] ? vc.pageTitle : nil;
				
				//[_buttons[i] setTitle:title ? title : vc.navigationItem.title forState:UIControlStateNormal];
			}
		}
		
		if (_pageCount && !_viewBar)		//有按钮时添加页面指示器
		{
			_viewBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 3)];
			_viewBar.backgroundColor = [MRSkinManager skin].skinColor;
			[_viewBar setBorderWithWidth:0 radius:1.5 color:nil];
			
			[_selectView addSubview:_viewBar];
			[_selectView layoutIfNeeded];
			
			[self adjustOffset];
		}
	}
	else if (_selectView)
	{
		UISegmentedControl *segmented = (UISegmentedControl *)_selectView;
		[segmented addTarget:self action:@selector(segmentedChange) forControlEvents:UIControlEventValueChanged];
		_pageCount = segmented.numberOfSegments;
		
		for (NSInteger i=0; i<_pageCount; i++)
		{
			if (i < self.childViewControllers.count)
			{
				//UIViewController <MRPageDelegate> *vc = self.childViewControllers[i];
				//NSString *title = [vc respondsToSelector:@selector(pageTitle)] ? vc.pageTitle : nil;
				
				//[segmented setTitle:title ? title : vc.navigationItem.title forSegmentAtIndex:i];
			}
		}
	}
	
	if (self.childViewControllers.count) _pageCount = self.childViewControllers.count;
	[self.collectionView reloadData];
	
	if (_lastPage == -1) [self toggleToPage:0];
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	[_viewController viewWillAppear:animated];
	
	if (!_viewController && self.childViewControllers.count > _lastPage)
	{
		_viewController = self.childViewControllers[_lastPage];
		
		if ([_viewController respondsToSelector:@selector(pageWillShow)])
		{
			[_viewController pageWillShow];
		}
	}
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
	
	if (_viewController)
	{
		if ([_viewController respondsToSelector:@selector(pageWillHide)])
		{
			[_viewController pageWillHide];
		}
		
		_viewController = nil;
	}
}

- (void)viewWillDealloc
{
	[_buttons removeAllObjects];
	
	for (UIViewController *vc in self.childViewControllers)
	{
		[vc viewWillDealloc];
	}
	
	[super viewWillDealloc];
}

#pragma mark - 页面控制
- (void)addChildViewController:(UIViewController *)childController
{
	//设置颜色的目的为加载控制器
	if ([childController isKindOfClass:[UIViewController class]])
	{
		if (childController.automaticallyAdjustsScrollViewInsets && [childController isKindOfClass:[UITableViewController class]])
		{
			UITableView *tableView = (UITableView *)childController.view;
			UIEdgeInsets edgeInsets = tableView.scrollIndicatorInsets;
			if (edgeInsets.top == 0) edgeInsets.top += 64;
			tableView.contentInset = tableView.scrollIndicatorInsets = edgeInsets;
		}
		
		childController.view.backgroundColor = [MRSkinManager skin].backgroundColor;
		//childController.view.backgroundColor = [UIColor clearColor];
		[super addChildViewController:childController];
	}
}

/*===================================================================
 说明：
	点击目标
 ==================================================================*/
- (void)clickButton:(UIButton *)btn
{
	if (btn.selected) return;
	NSInteger page = [_buttons indexOfObject:btn];
	
	if (page < self.pageCount)
	{
		_animated = YES;
		[self selectPage:page animated:YES];
		
		//NSIndexPath *indexPath = [NSIndexPath indexPathForItem:page inSection:0];
		//[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
	}
}

- (void)selectButton:(UIButton *)btn selected:(BOOL)selected
{
	if (btn.selected != selected)
	{
		btn.selected = selected;
		
		CGFloat size = btn.titleLabel.font.pointSize;
		btn.titleLabel.font = selected ? [UIFont boldSystemFontOfSize:size] : [UIFont systemFontOfSize:size];
	}
}

- (void)segmentedChange
{
	UISegmentedControl *segmented = (UISegmentedControl *)self.selectView;
	if (segmented.selectedSegmentIndex < self.pageCount)
	{
		[self selectPage:segmented.selectedSegmentIndex animated:YES];
	}
}

- (void)showNavigationItemWithAnimated:(BOOL)animated
{
	//当前控制器为导航控制器根视图时显示左导航内容
	if (!_leftItemsCount && [self.navigationController.viewControllers indexOfObject:self] == 0)
	{
		[self.navigationItem setLeftBarButtonItems:_viewController.navigationItem.leftBarButtonItems animated:YES];
	}
	
	//右导航内容
	if (_rightItemsCount == 0)
	{
		[self.navigationItem setRightBarButtonItems:_viewController.navigationItem.rightBarButtonItems animated:YES];
	}
	
	[UIView animateWithDuration:(animated ? .2 : 0) animations:^{
		
		if (![_selectView isEqual:self.navigationItem.titleView])		//选择视图为titleView时不处理标题项
		{
			if (self.viewController.navigationItem.titleView)
			{
				self.navigationItem.titleView = self.viewController.navigationItem.titleView;
			}
			else
			{
				self.navigationItem.titleView = nil;
				self.navigationItem.title = self.viewController.navigationItem.title;
			}
		}
		
		self.navigationItem.hidden = self.viewController.navigationItem.hidden;
		self.navigationItem.alpha  = self.viewController.navigationItem.alpha;
		self.navigationItem.hidesLine = self.viewController.navigationItem.hidesLine;
		self.navigationItem.barTintColor = self.viewController.navigationItem.barTintColor;
	}];
}

/*===================================================================
 说明:
	切换当前页面
 ==================================================================*/
- (void)toggleToPage:(NSInteger)page
{
	if (self.childViewControllers.count > page)
	{
		if ([_viewController respondsToSelector:@selector(pageWillHide)])
		{
			[_viewController pageWillHide];
		}
		
		_viewController = self.childViewControllers[page];

		if ([_viewController respondsToSelector:@selector(pageWillShow)])
		{
			[_viewController pageWillShow];
		}
		
		[self showNavigationItemWithAnimated:NO];
		[self setNeedsStatusBarAppearanceUpdate];
	}
	
	_lastPage = page;
	self.currentPage = page;
	
	if ([_selectView isKindOfClass:[UISegmentedControl class]])
	{
		UISegmentedControl *segmented = (UISegmentedControl *)self.selectView;
		segmented.selectedSegmentIndex = page;
	}
	
	for (NSInteger i=0; i<_buttons.count; i++)
	{
		[self selectButton:_buttons[i] selected:(i == page)];
	}
}

/*===================================================================
 说明:
	选择页面
 ==================================================================*/
- (void)selectPage:(NSInteger)page animated:(BOOL)animated
{
	NSInteger lastPage = self.collectionView.contentOffset.x / self.collectionView.bounds.size.width;
	if (page == lastPage && _lastPage >= 0) return;
	
	if (animated)
	{
		self.snapshot = [self.collectionView snapshotViewAfterScreenUpdates:NO];
		[self.view insertSubview:self.snapshot belowSubview:self.collectionView];
		
		self.collectionView.frame = CGRectOffset(self.view.bounds, self.view.bounds.size.width * (page > lastPage ? 1 : -1), 0);
	}
	
	NSIndexPath *indexPath = [NSIndexPath indexPathForItem:page inSection:0];
	[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
	
	[self toggleToPage:page];		//切换到新页面
	[self scrollViewDidEndDecelerating:self.collectionView];		//释放旧页面
	[self didSelectPage:page animated:animated];
	
	//切换动画
	__weak MRPageController *this = self;
	[UIView animateWithDuration:(animated ? .25 : 0) animations:^{
		this.snapshot.frame = CGRectOffset(this.view.bounds, this.view.bounds.size.width * (page > lastPage ? -1 : 1), 0);
		this.collectionView.frame = this.view.bounds;
		
	} completion:^(BOOL finished) {
		[this.snapshot removeFromSuperview];
		this.snapshot = nil;
	}];
	
	if (!IOS8 && !self.created) [_viewController viewWillAppear:NO];
}

- (void)didSelectPage:(NSInteger)page animated:(BOOL)animated
{
	//
}

#pragma mark - 视图管理
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewFlowLayout *)layout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
	//DFRAME(collectionView.frame);
	return UIEdgeInsetsInsetRect(collectionView.frame, layout.sectionInset).size;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
	return self.pageCount;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
	UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
	
	//iOS7 不支持willDisplayCell方法，不建议再支持iOS7
	if (!IOS8) [self collectionView:collectionView willDisplayCell:cell forItemAtIndexPath:indexPath];
	
	return cell;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
	if (collectionView == self.collectionView && self.childViewControllers.count > indexPath.row)
	{
		UIView *view = cell.contentView.subviews.firstObject;
		[view removeConstraintFromSuperview];
		[view removeFromSuperview];
		
		view = self.childViewControllers[indexPath.row].view;
		[view addConstraintEqualSuperview:cell.contentView];
	}
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
	if (scrollView != self.collectionView) return;
	
	CGPoint center = CGPointMake(CGRectGetMidX(self.collectionView.bounds), CGRectGetMidY(self.collectionView.bounds));
	NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:center];
	
	if (self.childViewControllers.count)
	{
		for (NSInteger i=0; i<self.childViewControllers.count; i++)
		{
			id <MRPageDelegate> vc = self.childViewControllers[i];
			if ([vc respondsToSelector:@selector(didScrollOffset:)])
			{
				[vc didScrollOffset:self.collectionView.contentOffset.x - i * self.view.bounds.size.width];
			}
		}
	}
	
	if (!_animated && indexPath.row != _lastPage)		//中位完成页面选择
	{
		[self toggleToPage:indexPath.row];
		[self didSelectPage:indexPath.row animated:YES];
	}
	
	[self adjustOffset];
}

/*===================================================================
 说明：
	滚动结束时释放旧视图
 ==================================================================*/
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
	if (scrollView == self.collectionView)
	{
		NSInteger page = self.collectionView.contentOffset.x / self.collectionView.bounds.size.width;
		for (NSInteger i=0; i<self.childViewControllers.count; i++)
		{
			if (i != page)
			{
				UIView *view = self.childViewControllers[i].view;
				[view removeConstraintFromSuperview];
				[view removeFromSuperview];
			}
		}
	}
}

/*===================================================================
 说明：
	指示器位置
 ==================================================================*/
 - (void)adjustOffset
{
	if (!_buttons.count) return;
	
	[UIView animateWithDuration:(_animated ? .25 : 0) animations:^{
		CGFloat x1 = 0, w1 = 0;
		CGFloat x2 = self.collectionView.bounds.size.width, w2 = 0;
		
		CGFloat offset = self.collectionView.contentOffset.x / self.collectionView.bounds.size.width;
		CGFloat center = offset - floor(offset);
		
		//获取第一个按钮中心及大小
		if (offset >= 0)
		{
			UIButton *btn = _buttons[lrint(floor(offset))];
			[self selectButton:btn selected:(center < .5)];
			
			x1 = btn.center.x;
			w1 = [btn.titleLabel textRectForBounds:btn.bounds limitedToNumberOfLines:1].size.width * 1.6;
			if (w1 > btn.bounds.size.width) w1 = btn.bounds.size.width;
		}
		
		//下个按钮中心及大小
		if (center && ceil(offset) < _buttons.count)
		{
			UIButton *btn = _buttons[lrint(ceil(offset))];
			[self selectButton:btn selected:(center >= .5)];
			
			x2 = btn.center.x;
			w2 = [btn.titleLabel textRectForBounds:btn.bounds limitedToNumberOfLines:1].size.width * 1.6;
			if (w2 > btn.bounds.size.width) w2 = btn.bounds.size.width;
		}
		
		//根据偏移确定指标器位置及大小
		_viewBar.bounds = CGRectMake(0, 0, w1 + (w2 - w1) * center, 2);
		_viewBar.center = CGPointMake(x1 + (x2 - x1) * center, _selectView.bounds.size.height - 1);
	}];
	
	_animated = NO;
}

@end
